import type { PiniaPluginContext } from "pinia";
// pinia 刷新不重置
class Storage {
  setItem(key: string, val: any) {
    console.log(key, val);
    localStorage.setItem(key, JSON.stringify(val));
  }
  getItem(key: string) {
    return JSON.parse(localStorage.getItem(key) as string) || "";
  }
}
const storage = new Storage();
const __defName__ = "pinia";
type Options = {
  key: string;
};
export const piniaStorage = (options?: Options) => {
  return (ctx: PiniaPluginContext) => {
    const { store } = ctx;
    // 只有响应式数据 store.$state才能获取到
    console.log("store", store);
    const data = storage.getItem(`pinia-${store.$id}`);
    store.$subscribe(() => {
      storage.setItem(
        `${options?.key ?? __defName__}-${store.$id}`,
        store.$state
      );
    });
    return { ...data };
  };
};
